function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}
	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time
	return ([hour, minute, second]).map(function(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}
	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)
	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}

var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function(milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function(dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function(number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDay()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
}

// 格式化时间
function getFormatTime(time) {
	var myDate = new Date();
	if (time) {
		myDate = new Date(time.replace(/-/g,'/'));
	}
	var _format = function(number) {
		return (number < 10 ? ('0' + number) : number);
	};
	var year = myDate.getFullYear();
	var month = _format(myDate.getMonth() + 1);
	var date = _format(myDate.getDate());
	var hours = _format(myDate.getHours());
	var minuts = _format(myDate.getMinutes());
	var seconds = _format(myDate.getSeconds());
	var today = year + '-' + month + '-' + date; // 2018-10-01
	var nowTime = hours + ':' + minuts + ':' + seconds; // 17:40:30
	var todayTime = today + ' ' + nowTime; // 2018-10-01 17:40:30
	var hours_minuts = hours + ':' + minuts; // 17:41
	return {
		year,
		month,
		date,
		hours,
		minuts,
		seconds,
		today,
		nowTime,
		todayTime,
		hours_minuts
	}
}

// uni-app接口统一处理
var imgHandle = {
	// 获取当前的地理位置
	getLocation: function() {
		return new Promise((resolve, reject) => {
			uni.getLocation({
				success: (res) => {
					var location = formatLocation(res.longitude, res.latitude)
					var e = location.longitude[0] + "." + location.longitude[1];
					var n = location.latitude[0] + "." + location.latitude[1];
					resolve(e + "," + n);
				},
				fail: (err) => {
					reject(err);
				}
			})
		})
	},
	// 调起客户端扫码界面
	scanCode: function(onlyFromCamera) {
		return new Promise((resolve, reject) => {
			uni.scanCode({
				onlyFromCamera: onlyFromCamera || false,
				success: (res) => {
					resolve(res)
				},
				fail: (err) => {
					reject(err);
				}
			});
		})
	},
	// 从本地相册选择图片或使用相机拍照。
	chooseImage: function(count, sizeType, sourceType) {
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: count || 9, //默认9
				sizeType: sizeType, //可以指定是原图还是压缩图，默认二者都有
				sourceType: sourceType, //使用相机
				success: (res) => {
					resolve(res.tempFilePaths[0]);
				},
				fail: (err) => {
					reject(err);
				}
			});
		})
	},
	// 预览图片。
	previewImage: function(urls) {
		uni.previewImage({
			urls: [urls]
		});
	},
	// 保存文件到本地。
	saveFile: function(tempFilePath) {
		return new Promise((resolve, reject) => {
			uni.saveFile({
				tempFilePath: tempFilePath,
				success: (res) => {
					resolve(res.savedFilePath);
				},
				fail: (err) => {
					reject(err);
				}
			});
		})
	},
	// 获取本地已保存的文件列表。
	getSavedFileList: function() {
		return new Promise((resolve, reject) => {
			uni.getSavedFileList({
				success: (res) => {
					resolve(res.fileList);
				},
				fail: (err) => {
					reject(err);
				}
			});
		})
	},
	// 删除本地存储的文件。
	removeSavedFile: function(filePath) {
		return new Promise((resolve, reject) => {
			uni.removeSavedFile({
				filePath: filePath,
				success: (res) => {
					resolve(res);
				},
				fail: (err) => {
					reject(err);
				}
			});
		})
	},
	// 保存图片到系统相册
	saveImageToPhotosAlbum: function(filePath) {
		return new Promise((resolve, reject) => {
			uni.saveImageToPhotosAlbum({
				filePath: filePath,
				success: (res) => {
					resolve(res);
				},
				fail: (err) => {
					reject(err);
				}
			});
		})
	},
	// 将本地资源上传到开发者服务器
	uploadFile: function(url, filePath, name) {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: url,
				filePath: filePath,
				name: name,
				success: (res) => {
					resolve(res.data);
				},
				fail: (err) => {
					reject(err);
				}
			});
		})
	},
	// 下载文件资源到本地
	downloadFile: function(url) {
		return new Promise((resolve, reject) => {
			uni.downloadFile({
				url: url,
				success: (res) => {
					if (res.statusCode === 200) {
						console.log('下载成功');
					}
					resolve(res);
				},
				fail: (err) => {
					reject(err);
				}
			});
		})
	}
}
function friendlyDate(datetime) {
	if(!datetime) return "";
	var timestamp=new Date(datetime.toString().replace(/\-/g, '/')).getTime()
	var formats = {
		'year': '%n% 年前',
		'month': '%n% 月前',
		'day': '%n% 天前',
		'hour': '%n% 小时前',
		'minute': '%n% 分钟前',
		'second': '%n% 秒前',
	};

	var now = Date.now();
	var seconds = Math.floor((now - timestamp) / 1000);
	var minutes = Math.floor(seconds / 60);
	var hours = Math.floor(minutes / 60);
	var days = Math.floor(hours / 24);
	var months = Math.floor(days / 30);
	var years = Math.floor(months / 12);

	var diffType = '';
	var diffValue = 0;
	if (years > 0) {
		return datetime;
	} else {
		if (months > 0) {
			return datetime;
		} else {
			if (days > 0) {
				return datetime;
			} else {
				if (hours > 0) {
					diffType = 'hour';
					diffValue = hours;
				} else {
					if (minutes > 0) {
						diffType = 'minute';
						diffValue = minutes;
					} else {
						diffType = 'second';
						diffValue = seconds === 0 ? (seconds = 1) : seconds;
					}
				}
			}
		}
	}
	return formats[diffType].replace('%n%', diffValue);
}

module.exports = {
	friendlyDate:friendlyDate,
	formatTime: formatTime,
	formatLocation: formatLocation,
	dateUtils: dateUtils,
	getFormatTime,
	imgHandle
}
